import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Http, Response, Headers } from '@angular/http';
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";
import { ResponseModel } from '../model/BaseModel/response-model';
import { Constant } from '../constant/constant';

@Injectable()
export class QuestionService {
  private Header = new Headers({'Content-Type': 'application/json'});
  private constant = new Constant;

  constructor(public http: Http) {}

  public questionList(userId: string): Observable<ResponseModel> {
    return this.http.post(this.constant.url + '/api/v1/getPaperInfo', JSON.stringify({'userId': userId}), {
      headers: this.Header})
      .map((res: Response) => {
        return res.json() as ResponseModel;
      })
      .catch(this.handleError);
  }

  public commitPaper(userId: string, paperId: string, answerInfo: any): Observable<ResponseModel> {
    return this.http.post(this.constant.url + '/api/v1/commit', JSON.stringify({'userId': userId, 'paperId': paperId, 'answerInfo': answerInfo}),
      {headers: this.Header})
      .map((res: Response) => {
        return res.json() as ResponseModel;
      })
      .catch(this.handleError);
  }

  public handleError(error: any): Observable<any> {
    alert('服务器连接失败，请稍后重试');
    return Observable.throw(error.message || error);
  }
}
